/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.guobo.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.OperationWebServiceUtils;
import com.thinkgem.jeesite.modules.guobo.dao.AssetDao;
import com.thinkgem.jeesite.modules.guobo.dao.RwDao;
import com.thinkgem.jeesite.modules.guobo.dao.WarningRoleDao;
import com.thinkgem.jeesite.modules.guobo.entity.Asset;
import com.thinkgem.jeesite.modules.guobo.entity.Rw;
import com.thinkgem.jeesite.modules.guobo.entity.WarningRole;

/**
 * 预警规则Service
 * @author wudavid
 * @version 2017-03-09
 */
@Service
@Transactional(readOnly = true)
public class WarningRoleService extends CrudService<WarningRoleDao, WarningRole> {

	@Autowired
	private AssetDao assetDao;
	
	@Autowired
	private RwDao rwDao;
	
	public WarningRole get(String id) {
		return super.get(id);
	}
	
	public List<WarningRole> findList(WarningRole warningRole) {
		return super.findList(warningRole);
	}
	
	public Page<WarningRole> findPage(Page<WarningRole> page, WarningRole warningRole) {
		return super.findPage(page, warningRole);
	}
	
	@Transactional(readOnly = false)
	public void save(WarningRole warningRole) {
		super.save(warningRole);
	}
	
	@Transactional(readOnly = false)
	public void delete(WarningRole warningRole) {
		super.delete(warningRole);
	}
	
	@Transactional(readOnly = false)
	public String saveWarningRole(WarningRole warningRole) {
		if (warningRole.getIsNewRecord()){
			warningRole.preInsert();
			dao.insert(warningRole);
		}else{
			warningRole.preUpdate();
			dao.update(warningRole);
		}
		return warningRole.getId();
	}
	
	/**
	 * 布控规则
	 * @param warningRole 预警规则
	 * @return 布控成功返回0,1为布控失败
	 */
	@Transactional(readOnly = false)
	public String rwDispatch(WarningRole warningRole) throws Exception{
		List<Rw> rws = rwDao.findRwByRoleId(warningRole.getId());
		List<String> rwids = new ArrayList<String>();
		for (Rw rw : rws) {
			rwids.add(rw.getId());
		}
		List<Asset> assets = assetDao.findAssetsByRoleId(warningRole.getId());
		List<String> rfids = new ArrayList<String>();
		for (Asset asset : assets) {
			rfids.add(asset.getRfid());
		}
		String result = OperationWebServiceUtils.dispatch("YES", rwids, rfids);
		if("0".equals(result)){
			warningRole.setStatus("01");
			dao.update(warningRole);
			for (Rw rw : rws) {
				rw.setDispatchStatus("1");
				rwDao.update(rw);
			}
		}
		return result;
	}
}